import { Injectable } from '@angular/core';
import { ServiceBase } from "./serviceBase";
import { Inventory, Category, DataContextManager, Cart, Modifier } from "../model/clerkDataContext";
import { guid } from "../common/guid";

@Injectable()
export class CartService extends ServiceBase {
    private cartItemList: Cart[] = [];
    constructor() {
        super();
    }
    get CartList() { return this.cartItemList; }

    GetLastCartItem(): Cart {
        if (this.cartItemList.length > 0)
            return this.cartItemList[this.cartItemList.length - 1];
        else return null;
    }
    CacheCart() {
        let ctx = DataContextManager.Current.ClerkCtx;
        this.cartItemList.forEach(x => {
            let item = new Cart();
            item = item.clone(x, item);
            ctx.Create(item);
        });
    }

    get TotalAmount(): number {
        let r: number = 0;
        this.cartItemList.forEach(x => {
            r += x.amount;
        });
        return r;
    }

    Clear() {
        this.cartItemList = [];
        //TODO:清空Indexeddb 中的购物车数据
    }

    GetCartItemByInventoryId(inventroyId: string): Cart {
        return this.cartItemList.find(x => x.inventoryId == inventroyId);
    }
    /**
     * 通过查询条件查找购物车商品项
     * @param  {CartQueryParams} param
     */
    QueryCartList(param: CartQueryParams) {
        let result = [];
        let qfnList = [];
        let where: (queryFuc: (entity: Cart) => boolean) => void = (qfn) => {
            qfnList.push(qfn);
        }
        if (param) {
            if (param.inventoryId) where(x => x.inventoryId == param.inventoryId);
            if (param.cartId) where(x => x.id == param.cartId);
        }

        if (this.cartItemList && this.cartItemList.length) {
            for (let value of this.cartItemList) {
                let flag = true;
                for (let qfnc of qfnList) {
                    if (!qfnc(value)) {
                        flag = false;
                        break;
                    }
                }
                if (flag) result.push(value);
            }
        }
        return result;
    }
    /**
     * 通过商品id查询购物车中对应商品最新的一项
     * @param  {string} inventroyId
     */
    GetLastCartItemByInventoryId(inventroyId: string) {
        let inventroyList = [];
        let result = null;
        inventroyList = this.QueryCartList({ inventoryId: inventroyId });
        if (inventroyList && inventroyList.length) {
            result = inventroyList[inventroyList.length - 1];
        }
        return result;
    }
    /**
     * 根据商品Id获取不带偏好的购物车项
     * @param  {string} inventroyId
     * @returns Cart
     */
    GetNormalCartItemByInventoryId(inventroyId: string): Cart {
        return this.cartItemList.find(x => {
            return x.inventoryId == inventroyId && (!x.modifiers || x.modifiers.items.length == 0);
        });
    }
    
    UpdateCart(cart: Cart) {
        let target = undefined;
        for (let i = 0; i < this.cartItemList.length; i++) {
            if (this.cartItemList[i].id == cart.id) {
                target = this.cartItemList.splice(i ,1);
                target = cart;
                break;
            }
        }
        if(target){
            this.cartItemList.push(target);
        }
        console.log("UpdateCart", this.cartItemList);
    }
    AddCart(cart: Cart) {
        this.cartItemList.push(cart);

        console.log("AddCart", this.cartItemList);

    }
    RemoveCart(cart: Cart) {
        let index = this.cartItemList.findIndex(x => x.id == cart.id);
        this.cartItemList.splice(index, 1);
        console.log("RemoveCart", this.cartItemList);
    }

    /**
     * 判断两个偏好是否一致
     * @param s 对比偏好一
     * @param d 对比偏好二
     * @return boolean ture一致，false不一致
     */
    ModifiyComparison(s: Modifier[], d: Modifier[]): boolean {
        if (s.length != d.length) return false;

        for (let i = 0; i < s.length; i++) {
            let dd = d.find(n => n.name == s[i].name);
            if (dd) {
                if (dd.options != s[i].options) return false;
                if (dd.options && s[i].options) {
                    if (dd.options.length != s[i].options.length) return false;
                    s[i].options.forEach(opt => {
                        let ddop = dd.options.find(nn => nn.name == opt.name);
                        if (!ddop) return false;
                    });
                }
            }
            else return false;
        }

        return true;
    }

    CreateCartItem(inventory: Inventory, modifiers: { amount: number; items: Modifier[] }) {
        let cartItem = new Cart();
        cartItem.id = guid();
        cartItem.inventory = inventory;
        cartItem.inventoryCode = inventory.code;
        cartItem.inventoryId = inventory.id;
        cartItem.inventoryName = inventory.name;
        cartItem.amount = inventory.price;
        cartItem.qty = 1;
        cartItem.modifiers = modifiers;
        cartItem.price = inventory.price;
        cartItem.costPrice = inventory.costPrice;
        cartItem.extended = { categories: inventory.categories };

        return cartItem;
    }
}

export interface CartQueryParams {
    inventoryId?: string;
    cartId?: string;
}